<template>
  <div class="exam-wrapper">
    <div class="header" ref="domRef">
      {{ mapText[Number($route.params.id)] || '无标题' }}
    </div>
    <div class="wrapper-qs">
      <el-scrollbar
        v-if="questionList.length"
        style="height: calc(100% - 50px)"
      >
        <div
          class="exam-item"
          v-for="(item, index) in questionList"
          :key="item.id"
        >
          <div class="content" style="padding: 0 10px 0 0">
            <div class="qs-header-title">
              <div>
                <el-button type="primary" id="top" round>
                  {{ STATIC_QUESTION_TYPE[item.type] }}
                </el-button>
                【{{ STATIC_QSRANK_TYPE[item.difficulty] }}】
                <el-text
                  v-if="QuestionType.fill === item.type"
                  style="color: var(--el-color-warning); margin-left: 10px"
                >
                  注意事项：
                  {{ `(答案:${QuestionOrderText[item.is_order]})` }}
                </el-text>
              </div>
              <el-button
                v-if="Number($route.params.id) !== 3"
                round
                @click="handleRemoveQuestion(item)"
              >
                移出{{
                  CollectOrError.collect === Number($route.params.id)
                    ? '收藏夹'
                    : '错题本'
                }}
              </el-button>
            </div>
            <div class="qs-content">
              <markdown-viewer id="assistant-content" :value="item.content" />
              <!-- 单选 多选 判断  -->
              <div class="options" v-if="item.options && item.options?.length">
                <div
                  class="opt-item"
                  v-for="(opt, index) in JSON.parse(item.options)"
                >
                  <el-radio-group
                    v-if="
                      QuestionType.radio === item.type ||
                      QuestionType.judge === item.type
                    "
                    v-model="item.user_answer"
                  >
                    <el-radio :value="mapIndex[index]" disabled>
                      <markdown-viewer :id="`opt-item` + index" :value="opt" />
                    </el-radio>
                  </el-radio-group>
                  <el-checkbox-group
                    v-else-if="QuestionType.checkbox === item.type"
                    v-model="item.user_answer"
                  >
                    <el-checkbox :value="mapIndex[index]" disabled>
                      <markdown-viewer :id="`opt-item` + index" :value="opt" />
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </div>
              <!-- 填空题 -->
              <div class="fill" v-else-if="item.type === QuestionType.fill">
                <div class="fill-item" v-for="(child, index) in item.fills">
                  答案:
                  {{ index + 1 }}
                  <div
                    style="border-bottom: 1px solid #ccc; width: 100%"
                    v-if="child.fill"
                  >
                    <markdown-viewer id="answer" :value="child.fill" />
                  </div>
                  <div
                    v-else
                    style="border-bottom: 1px solid #ccc; width: fit-content"
                    class="fill-input-container"
                  >
                    <el-input
                      type="text"
                      readonly
                      v-model="child.fill"
                      placeholder="请输入答案"
                      class="fill-input"
                      :input-style="{
                        border: 'none',
                        boxShadow: 'none !important',
                      }"
                      style="border: none !important"
                    ></el-input>
                  </div>
                </div>
              </div>
              <!-- 简答题 -->
              <div v-else-if="selectedQuestion.type === QuestionType.short">
                <markdown-viewer
                  v-if="item.user_answer"
                  id="short-answer"
                  :value="item.user_answer"
                />
                <el-input
                  v-else
                  type="textarea"
                  v-model="item.user_answer"
                  placeholder="请输入答案"
                  class="fill-input"
                  :input-style="{
                    border: 'none',
                  }"
                ></el-input>
              </div>
            </div>
          </div>
          <div class="anwer-explain">
            <!-- 答案  -->
            <div class="flex align-items-center">
              <div style="flex-shrink: 0"><b>正确答案:</b></div>
              <div v-if="QuestionType.fill == item.type">
                <markdown-viewer id="answer" :value="item.answer" />
              </div>
              <span v-else>
                {{ item.answer }}
              </span>
            </div>
            <div class="flex align-items-center">
              <div style="flex-shrink: 0"><b>你的答案:</b></div>
              <div
                v-if="
                  QuestionType.fill == item.type ||
                  QuestionType.short == item.type
                "
              >
                <span
                  v-if="item.user_answer"
                  style="color: var(--el-color-primary)"
                >
                  如题干所示
                </span>
              </div>
              <span v-else>
                {{
                  QuestionType.checkbox == item.type
                    ? formatMultiAnswer(item.user_answer.join(''))
                    : item.user_answer
                }}
              </span>
            </div>
            <div
              class="question-rate"
              style="
                display: flex;
                align-items: baseline;
                justify-content: space-between;
                gap: 10px;
              "
            >
              <div class="right-rate">
                <b>正确率:</b>
                <span style="color: var(--el-color-success);margin-left:4px">
                  {{ (item.right_rate * 100).toFixed(2) }}%
                </span>
                <b>错误率:</b>
                <span style="color: var(--el-color-danger);margin-left:4px">
                  {{ ((1 - Number(item.right_rate)) * 100).toFixed(2) }}%
                </span>
              </div>
            </div>
            <!-- 解析 -->
            <div class="">
              <div style="flex-shrink: 0"><b>解析:</b></div>
              <markdown-viewer
                v-if="item.analysis"
                id="explain"
                :value="item.analysis"
              />
              <span v-else>无</span>
            </div>
            <div style="display: flex; align-items: center; gap: 10px">
              <b style="flex-shrink: 0">相关知识点:</b>
              <el-text truncated style="margin-top: 4px">
                {{ item.keyword_name }}
              </el-text>
            </div>
          </div>
        </div>
      </el-scrollbar>
      <el-empty v-else></el-empty>
      <div class="pagination" v-if="questionList.length < totalCount">
        <pagination
          :total="totalCount"
          v-model:page="query.page"
          v-model:limit="query.limit"
          @pagination="getQuestionsInit"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import MarkdownViewer from '@/components/markdown-viewer/index.vue'
import Pagination from '@/components/pagination/index.vue'
import {
  QuestionType,
  STATIC_QUESTION_TYPE,
  CollectOrError,
  QuestionOrderText,
  STATIC_QSRANK_TYPE,
} from '@/enum/study'
import {
  httpRemoveCollectOrError,
  httpQsCollectOrError,
  httpEasyErrorQuestions,
} from '@/api/study'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
const selectedQuestion = ref<any>({})
const questionList = ref([])
const route = useRoute()
const mapIndex = {
  0: 'A',
  1: 'B',
  2: 'C',
  3: 'D',
  4: 'E',
  5: 'F',
  6: 'G',
  7: 'H',
}
const mapText = {
  1: '题目收藏',
  2: '错题本',
  3: '易错题',
}
const query = reactive({
  page: 1,
  limit: 20,
  type: Number(route.params.id),
})
const totalCount = ref(0)
const sortArr = (arr) => {
  let radio = arr.filter((item) => item.type === QuestionType.radio)
  let checkbox = arr.filter((item) => {
    if (item.type === QuestionType.checkbox) {
      item.select = formatMultiAnswer(item.user_answer)
      let arr = item.user_answer.split('')
      item.user_answer = arr
      return item
    }
  })
  let judge = arr.filter((item) => item.type === QuestionType.judge)
  let fill = arr.filter((item) => {
    if (item.type === QuestionType.fill) {
      let arr = item.user_answer.split('|')
      item.fills = item.answer.split('|').map((item, index) => {
        return {
          index,
          id: index,
          fill: arr.length && arr[index] ? arr[index].trim() : '',
        }
      })
      return item
    }
  })

  let short = arr.filter((item) => item.type === QuestionType.short)
  return [...radio, ...checkbox, ...judge, ...fill, ...short].map(
    (item, index) => ({
      ...item,
      // sort: index + 1,
      questionIndex: index,
      sort:
        query.page === 1
          ? index + 1
          : (query.page - 1) * query.limit + index + 1,
    }),
  )
}
const mergedArray = (arr) => {
  return arr.reduce((acc, current) => {
    const existing = acc.find((item) => item.type === current.type)
    if (existing) {
      existing.children.push(current)
    } else {
      acc.push({ type: current.type, children: [current] })
    }
    return acc
  }, [])
}

const formatMultiAnswer = (answer = '') => {
  return answer.toUpperCase().split('').sort().join('')
}

const handleRemoveQuestion = async (item) => {
  const res = await httpRemoveCollectOrError({
    question_id: item.id,
    // type: CollectOrError.error,
    type: query.type,
  })
  if (res) {
    getQuestionsInit()
  }
}

const getQuestionsInit = async () => {
  let res: any = []
  if ([1, 2].includes(Number(route.params.id))) {
    res = await httpQsCollectOrError({
      ...query,
    })
  } else if (Number(route.params.id) === 3) {
    let params = { ...query }
    delete params.type
    res = await httpEasyErrorQuestions(query)
  }

  if (res) {
    totalCount.value = res.total
    questionList.value = sortArr(res.list)
  }
}
onMounted(() => {
  //
  if (![1, 2, 3].includes(Number(route.params.id))) {
    return ElMessage.error('访问地址错误')
  }
  getQuestionsInit()
})
</script>

<style scoped lang="scss">
.exam-wrapper {
  height: 100%;
  .header {
    height: 40px;
    line-height: 40px;
    font-weight: bold;
    font-size: 18px;
    border-bottom: 1px solid #ccc;
  }
  .wrapper-qs {
    width: calc(100%);
    height: calc(100% - 40px);
  }
  .exam-item {
    box-shadow: var(--el-box-shadow-light);
    border-radius: var(--el-border-radius-base);
    background-color: #fff;
    margin: 10px;
    padding: 10px;
    .qs-header-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;

      .collect-qs {
        border: 1px solid #ccc;
        border-radius: 5px;
        padding: 4px 10px;
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }
    .qs-content {
      .opt-item {
        margin-bottom: 10px;
      }
      :deep(.el-radio) {
        height: fit-content !important;
      }
      :deep(.el-checkbox) {
        height: fit-content !important;
      }
    }
    .anwer-explain {
      .answer {
        word-wrap: break-word;
        padding: 10px 0;
      }
      .explain {
        word-wrap: break-word;
        padding: 10px 10px 10px 0;
      }
    }
  }
}

.fill-input {
  border: none !important;
}
.fill-input-container {
  :deep(.el-input__wrapper) {
    box-shadow: none !important;
    border: none !important;
    padding: 0 !important;
  }
}
</style>
